package com.fyzk.activity.trend;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.tyjc.unique.bean.SSQTrendChart;
import com.tyjc.unique.common.ZouShiInfors;
import com.tyjc.unique.net.UrlConstants;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.lottery.shuzicai.BallInfo;
import com.fyzk.activity.lottery.shuzicai.klpk.KLPKPopupwindow;
import com.fyzk.activity.zhifu.NumLotteryZhiFuActivity;
import com.fyzk.activity.zoushitu.ZST_sheZhi;
import com.fyzk.bean.CurrentPhaseInfo;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.betcode.BetLotteryInfo;
import com.fyzk.betcode.CodeFactory;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.view.TrendTopView;
import com.fyzk.view.ViewCallBack;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.Common.SchemaDef;
import com.wf.domain.UrlDef;
import http.StringResultBean;

/**
 * Created by fanxs11 on 2017/7/16.
 */
@ContentView(R.layout.ac_trend)
public abstract class TrendBaseActivity extends BaseActivity implements KLPKPopupwindow.KLPKPopuponItemListener,
        ViewCallBack.CountDownInterface, OnTrendBallClick {

    @ViewInject(R.id.trend_topview)
    protected TrendTopView topView;

    @ViewInject(R.id.trend_choose_ll)
    protected LinearLayout choose_ll;

    @ViewInject(R.id.trend_center_ll)
    LinearLayout center_ll;

    @ViewInject(R.id.trend_sure_btn)
    protected Button sure_btn;
    @ViewInject(R.id.trend_phase_tv)
    private TextView phase_tv;
    @ViewInject(R.id.trend_endtime_tv)
    private TextView endTime_tv;
    @ViewInject(R.id.trend_zhushu_tv)
    private TextView zhuShu_tv;
    @ViewInject(R.id.trend_zhushu_ll)
    protected LinearLayout zhuShu_ll;

    private int qiShu = 50;
    public int type = 0;

    protected TrendBaseView trendView;

    protected List<BallInfo> redBallInfos = new ArrayList<>();
    protected List<BallInfo> blueBallInfos = new ArrayList<>();
    protected List<List<BallInfo>> arrs = new ArrayList<>();

    protected int popupId = 0;  // 下拉菜单 选中item的id

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewCallBack.getInstance().AttachCountDownObj(this);
        popupId = getIntent().getIntExtra(IntentParamUtils.POPUPID, 0);

        topView.setOnTitleClickListener(this);
        topView.setJianTouVisible(getTopDownVisible());
        topView.setCenterText(getTopTitle()+"走势图");

        center_ll.removeAllViews();
        trendView = getTrendView();
        trendView.setLayerType(View.LAYER_TYPE_SOFTWARE,null);  // 对控件关闭硬件加速器
        trendView.setOnTrendBallClickListener(this);
        center_ll.addView(trendView);

        phase_tv.setText("距"+getPhase()+"期截止：");

        sure_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (trendView != null) {
                    saveCode(trendView.bottomInfors);
                }
            }
        });

        setSureBtnVisibility();

        View chooseView = getChooseView();
        if (chooseView != null) {
            choose_ll.addView(chooseView);
        }

        net();

        initBallList();

        if(MySharedPreferences.getInstance().getOpenStatus()){
            sure_btn.setVisibility(View.VISIBLE);
        }else{
            sure_btn.setVisibility(View.GONE);
        }
    }

    private void net() {
        findCurrentPhase();
        trendView.setStateData(TrendBaseView.STATE_REQUESTING);
        switch (getLotteryType()) {
            case LotteryIDUtils.SSQ_LOTTERY_ID_INT:
            case LotteryIDUtils.DLT_LOTTERY_ID_INT:
            case LotteryIDUtils.FC3D_LOTTERY_ID_INT:
            case LotteryIDUtils.PL3_LOTTERY_ID_INT:
            case LotteryIDUtils.PL5_LOTTERY_ID_INT:
            case LotteryIDUtils.QXC_LOTTERY_ID_INT:
                requestTrendChart();
                break;
            default:
                requestTrendChartNew();
                break;
        }
    }
    @Override
    protected void onDestroy() {
        AppLotteryCodeListManager.betType = AppLotteryCodeListManager.FIRSTENTER;
        AppLotteryCodeListManager.getInstance().getList().clear();
        AppLotteryCodeListManager.chooseId = 0;
        ViewCallBack.getInstance().DettachCountDownObj(this);
        super.onDestroy();
    }

    @Override
    public void finish() {
        // 清除投注
        AppLotteryCodeListManager.getInstance().getList().clear();
        AppLotteryCodeListManager.betType = AppLotteryCodeListManager.FIRSTENTER;
        AppLotteryCodeListManager.chooseId = 0;
        super.finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 0 && null != data) {
            trendView.isChangeTJ = false;
            trendView.isZX = data.getBooleanExtra(ZST_sheZhi.ZST_ZHEXIAN, false);
            trendView.isYL = data.getBooleanExtra(ZST_sheZhi.ZST_YILOU, false);
            if (trendView.isTJ != data.getBooleanExtra(ZST_sheZhi.ZST_TONGJI, false)) {
                trendView.isTJ = data.getBooleanExtra(ZST_sheZhi.ZST_TONGJI, false);
                trendView.isChangeTJ = true;
            }

            if (qiShu != data.getIntExtra(ZST_sheZhi.ZST_QISHU, 30)) {
                qiShu = data.getIntExtra(ZST_sheZhi.ZST_QISHU, 30);
                trendView.isChangeTJ = true;
                net();
            } else {
                trendView.setMissInfors(trendView.payType, trendView.chooseId);
                trendView.setInfors(trendView.getInfors(), trendView.phaseInfos, trendView.chooseId);
            }
        }
    }

    protected View getChooseView() {
        return null;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }

    protected void saveCode(List<TrendBaseView.Drawinfor> infors) {
        long zhuShu = getZhuShu(trendView.bottomInfors);
        if (zhuShu < 1) {
            AppToast.getToast().show("至少选择一注");
            return;
        }
        if (zhuShu > 10000) {
            AppToast.getToast().show("最多选择10000注");
            return;
        }
        for (TrendBaseView.Drawinfor drawinfor : infors) {
            if (drawinfor.isCheck) {
                switch (drawinfor.type) {
                    case 0:
                        List<BallInfo> ballInfos0 = arrs.get(0);
                        for (BallInfo ballInfo : ballInfos0) {
                            if (ballInfo.getNum().equals(drawinfor.text)) {
                                ballInfo.setSelected(true);
                            }
                        }
                        break;
                    case 1:
                        List<BallInfo> ballInfos1 = arrs.get(1);
                        for (BallInfo ballInfo : ballInfos1) {
                            if (ballInfo.getNum().equals(drawinfor.text)) {
                                ballInfo.setSelected(true);
                            }
                        }
                        break;
                    case 2:
                        List<BallInfo> ballInfos2 = arrs.get(2);
                        for (BallInfo ballInfo : ballInfos2) {
                            if (ballInfo.getNum().equals(drawinfor.text)) {
                                ballInfo.setSelected(true);
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        switch (getLotteryType()) {
            case LotteryIDUtils.SSQ_LOTTERY_ID_INT:

                ssqTouZhu1(arrs, zhuShu);
                break;
            case LotteryIDUtils.DLT_LOTTERY_ID_INT:
                dltTouZhu1(arrs, zhuShu);
                break;
            default:
                AppToast.getToast().show("准备中...");
                break;
        }

    }

    /**
     * 双色球投注
     * @param arrs
     * @param zhuShu
     */
    public void ssqTouZhu1(List<List<BallInfo>> arrs, long zhuShu) {
        // TODO Auto-generated method stub
//        StringBuffer strB = new StringBuffer();
        int wcodeId;
        if (zhuShu > 1) {
            wcodeId = LotteryIDUtils.SSQ_LOTTERY_COMMON_FU_ID_INT;
        } else {
            wcodeId = LotteryIDUtils.SSQ_LOTTERY_COMMON_DAN_ID_INT;
        }
        String Zhuma = getBetCode(trendView.bottomInfors);
        String showZhuMa =  CodeFactory.getCode(LotteryIDUtils.SSQ_LOTTERY_ID_INT).formatHtmlCode2(Zhuma);
        AppLotteryCodeListManager.getInstance().AddLotteryInfo(wcodeId, Zhuma,
                showZhuMa, zhuShu, arrs, 0);
        BetLotteryInfo betInfo = new BetLotteryInfo(wcodeId, Zhuma, showZhuMa,
                zhuShu, arrs, 0);
        Intent intent = new Intent(getContext(), NumLotteryZhiFuActivity.class);
        intent.putExtra(IntentParamUtils.LOTTERYID, LotteryIDUtils.SSQ_LOTTERY_ID_INT);
        intent.putExtra("bet", (Serializable) betInfo);
        startActivity(intent);
    }

    public void dltTouZhu1(List<List<BallInfo>> arrs, long zhuShu) {
        // TODO Auto-generated method stub
//        StringBuffer strB = new StringBuffer();
        int wcodeId;
        if (zhuShu > 1) {
            wcodeId = LotteryIDUtils.DLT_LOTTERY_COMMON_FU_ID_INT;
        } else {
            wcodeId = LotteryIDUtils.DLT_LOTTERY_COMMON_DAN_ID_INT;
        }
        String Zhuma = getBetCode(trendView.bottomInfors);
        String showZhuMa =   CodeFactory.getCode(LotteryIDUtils.DLT_LOTTERY_ID_INT).formatHtmlCode2(Zhuma);;
        AppLotteryCodeListManager.getInstance().AddLotteryInfo(wcodeId, Zhuma,
                showZhuMa, zhuShu, arrs, 0);
        BetLotteryInfo betInfo = new BetLotteryInfo(wcodeId, Zhuma, showZhuMa,
                zhuShu, arrs, 0);
        Intent intent = new Intent(getContext(), NumLotteryZhiFuActivity.class);
        intent.putExtra(IntentParamUtils.LOTTERYID, LotteryIDUtils.DLT_LOTTERY_ID_INT);
        intent.putExtra("bet", (Serializable) betInfo);
        startActivity(intent);
    }

    //初始化与小球界面绑定的数据
    private void initBallList() {
        initBallList(redBallInfos, 33, 1, true);
        initBallList(blueBallInfos, 16, 1, true);
        arrs.add(redBallInfos);
        arrs.add(blueBallInfos);
    }

    /**
     * 初始化 小球list
     *
     * @param balls
     * @param count 每列显示小球数
     * @param start
     */
    public void initBallList(List<BallInfo> balls, int count, int start,
                             boolean hasZero) {
        balls.clear();
        for (int j = start; j < count + start; j++) {
            BallInfo qiu;
            if (hasZero) {
                if (j < 10) {
                    qiu = new BallInfo("0" + j);
                } else {
                    qiu = new BallInfo("" + j);
                }
            } else {
                qiu = new BallInfo(String.valueOf(j));
            }
            balls.add(qiu);
        }
    }

    protected abstract String getBetCode(List<TrendBaseView.Drawinfor> infors);
    protected abstract long getZhuShu(List<TrendBaseView.Drawinfor> infors);
    protected String getPhase(){
        return AppLotteryInfos.getPeriod(getLotteryType());
    }
    protected long getEndTime() {
        return AppLotteryInfos.getEndTime(getLotteryType());
    }
    protected void setSureBtnVisibility() {
        sure_btn.setVisibility(View.GONE);
        zhuShu_ll.setVisibility(View.GONE);
    }

    protected String getTopTitle() {
        return AppLotteryInfos.getLotteryName(getLotteryType());
    }

    protected int getTopDownVisible(){
        return View.GONE;
    }
    protected TrendBaseView getTrendView() {
        return new TrendBaseView(getContext()) {
            @Override
            boolean isShowBottom(List<Drawinfor> infors) {
                return true;
            }
        };
    }

    protected void setInfors(List<List<Integer>> infors, List<String> phaseInfors) {
        if (trendView != null) {
            trendView.setInfors(infors, phaseInfors, trendView.chooseId);
        }
    }

    private void requestTrendChart() {

        RequestParams params = new RequestParams(UrlConstants.TEST);

        params.addBodyParameter("lotteryType", getLotteryType() + "");
        params.addBodyParameter("page", "1");
        params.addBodyParameter("count", "" + qiShu);

        sendRequest(HttpMethod.POST, SchemaDef.TREND_CHART, params, false);

    }

    /**
     * 查询走势
     */
    protected void requestTrendChartNew() {
        try {
            JSONObject params = new JSONObject();
            params.put("lotteryType", getLotteryType() + "");
            params.put("missName", AppLotteryInfos.getMissKey2(getLotteryType(), popupId));
            params.put("hotcoldName", AppLotteryInfos.getHCKey(getLotteryType(), popupId));
            params.put("basicMissName", AppLotteryInfos.getMissKey(getLotteryType(), popupId));
            params.put("num", ""+qiShu);
            httpPostJson(CommandUtil.MVDATALIST, "multipleData", params, false, UrlDef.TY_URL_NEW_DATA2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询新期
     */
    protected void findCurrentPhase() {
        try {
            JSONObject params = new JSONObject();
            params.put("lotteryType", getLotteryType());
            httpPostJson(CommandUtil.FINDCURRENTPHASE, Commands.FINDCURRENTPHASE, params, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean,
                             String result) {
        // TODO Auto-generated method stub
        trendView.setStateData(TrendBaseView.STATE_NORMAL);
        switch (requestCode) {
            case CommandUtil.FINDCURRENTPHASE:
                CurrentPhaseInfo info = JSON.parseObject(resultBean.getData(),
                        CurrentPhaseInfo.class);
                AppLotteryInfos.setCurrentPrizeInfo(info);
                break;
            case CommandUtil.MVDATALIST:
                TrendBean bean = getTrendBean(resultBean.getData());
                trendView.setTrendBean(bean);
                break;
            case SchemaDef.TREND_CHART:
                List<SSQTrendChart> arrayChartItems = JSON.parseArray(
                        resultBean.getValue(), SSQTrendChart.class);
                setInfors(ZouShiInfors.getZouShi(arrayChartItems), ZouShiInfors.getPhase(arrayChartItems));
                break;
        }

    }

    protected TrendBean getTrendBean(String json) {
        return JSON.parseObject(json, TrendBean.class);
    }

    @Override
    protected void onFailure(int requestCode) {
        // TODO Auto-generated method stub
        trendView.setStateData(TrendBaseView.STATE_ERROR);
        Log.d(TAG, "onFailure: 获取数据失败");
        trendView.setTrendBean(null);
    }

    protected int getLotteryType(){
        return getIntent().getIntExtra(IntentParamUtils.LOTTERYID, LotteryIDUtils.SSQ_LOTTERY_ID_INT);
    };


    @Override
    public void onLeftClick() {
        super.onLeftClick();
    }

    @Override
    public void onCenterClick() {

    }

    @Override
    public void onRightClick() {
        Intent intent = new Intent(getContext(), ZST_sheZhi.class);

        intent.putExtra(ZST_sheZhi.ZST_QISHU, qiShu);
        intent.putExtra(ZST_sheZhi.ZST_ZHEXIAN, trendView.isZX);
        intent.putExtra(ZST_sheZhi.ZST_YILOU, trendView.isYL);
        intent.putExtra(ZST_sheZhi.ZST_TONGJI, trendView.isTJ);

        startActivityForResult(intent, 0);
    }

    @Override
    public void onItem(int position) {
        popupId = position;
        net();
    }

    @Override
    public void popupShow() {

    }

    @Override
    public void popupDismiss() {

    }

    @Override
    public void countDown() {
        endTime_tv.setText(ViewCallBack.getInstance().refreshTimeLeft(
                AppLotteryInfos.getEndTime(getLotteryType())));
        phase_tv.setText("距"+getPhase()+"期截止：");
    }

    @Override
    public void onBallClick() {
        zhuShu_tv.setText(getZhuShu(trendView.bottomInfors)+"注");
    }
}
